import React, { memo,useCallback, useRef, useState } from 'react';
import { projectImport, projectExport, getExportState, getImportState } from '@/services/cpasRequest';
import { intl } from '@/utils';
import Toolbar, { Item } from 'devextreme-react/toolbar';
import DropDownButton from 'devextreme-react/drop-down-button';
import notify from 'devextreme/ui/notify';
import './index.less';
import TipsPopup from './TipsPopup';
import { Progress } from 'antd';
import PubSub from 'pubsub-js';
import { getIsCheckProjectIsOpened } from './service';
import SelZcbfPopup from './import/SelZcbfPopup';
const SelZcbfPopupMemo = memo(SelZcbfPopup);

const ToolHead = () => {
  const [treeZcbfids, setTreeZcbfids] = useState<any>([]);
  const [zcbfidsName, setZcbfidsName] = useState<any>([]);
  const [dataProjectBH, setDataProjectBH] = useState<any>('');
  const selZcbfPopupRef = useRef<any>();

  const [zcbfNameLength, setZcbfNameLength] = useState<any>(0);
  const [fileAddress, setFileAddress] = useState<any>({});
  const tipsPopup = useRef<any>(0);

  const [progressNumber, setProgressNumber] = useState<any>(0);

  const [isShowProgress, setIsShowProgress] = useState<boolean>(false);


  const getZcbfListData = useCallback((data: any) => {
    setTreeZcbfids(data.zcbfIDString);
    setZcbfidsName(data.zcbfsName);
    setZcbfNameLength(data.zcbfsNameLength);
    setDataProjectBH(data.projectBh);
  }, []);


  PubSub.unsubscribe('zcbfidsInfoTreeList');
  PubSub.subscribe('zcbfidsInfoTreeList', (msg: any, data: any) => {
    if (data.msg === 'zcbfidsInfo') {
      console.log('@@@', data.data);

      getZcbfListData(data.data);
    }
  });

  // const addNumber = () => {
  //   setTimeout(() => {
  //     if (progressNumber < 80) {
  //       setProgressNumber((num: number) => {
  //         const newData = num + 80;
  //         return newData;
  //       });
  //     }
  //   }, 2000);
  // }

  // 项目成果 点击事件
  const onItemClickAchievements = async (e: any) => {
    if (e.itemData === "成果导出") {
    } else if (e.itemData === "成果导入") {
    }
  }
  const onItemClickProject = async (e: any) => {
    if (e.itemData === "项目导出") {
      if (!treeZcbfids[0]) return notify({ message: `未选中任何导出的项目`, position: 'top center' }, "warning", 1000);
      const res = await getIsCheckProjectIsOpened({ zcbfid: treeZcbfids });
      if (res.success) {
        if (res.data) {
          notify({ message: `被审单位已经打开不能导出，请关闭打开的被审单位后再执行导出！`, position: 'top center' }, "warning", 2000);
        } else {
          const dialog_result = await window.electronComponents.showSaveDialog("aue6", `分发项目数据(${zcbfidsName}等${zcbfNameLength}个).aue6`);
          if (!dialog_result.canceled) {
            setProgressNumber(0);
            const checkFolderPath = dialog_result.filePath;
            const resParams = {
              zcbfIds: treeZcbfids,
              filePath: checkFolderPath
            };
            setIsShowProgress(true);
            try {
              const changeProcess = setInterval(async () => {
                const resState: any = await getExportState();
                setProgressNumber(resState.compressProcess);
              }, 1500);
              const res = await projectExport(resParams);
              if (res.ok) {
                notify({ message: `导出项目成功！`, position: 'top center' }, "success", 1000);
                clearInterval(changeProcess);
                setProgressNumber(100);
              } else {
                clearInterval(changeProcess);
                notify({ message: `导出项目失败：${res.data}`, position: 'top center' }, "error", 1000);
              }
              setTimeout(() => {
                setIsShowProgress(false);
              }, 500);
            } catch (error) {
              notify({ message: `导出项目失败：${error}`, position: 'top center' }, "error", 1000);
              setIsShowProgress(false);
              setProgressNumber(0);
            }
          }
        }
      }


    } else if (e.itemData === "项目导入") {

      // electronComponents // 打开系统文件夹 选择
      // 新增功能调出弹窗选择
      selZcbfPopupRef.current.showSelZcbfPopup();
      // 用户选择导入的文件进行文件解压
      // 数据查重，进行判断。
      // 用新的组建实现
   
    }
  }



  const SpinLoading = () => {
    return (
      <div className="headSpinLoading">
        <Progress percent={progressNumber} size="small" status="active" style={{ width: '40%' }} />
      </div>
    );
  };


  return (
    <>
      <div style={{ height: '58px' }} className='toolHead' >
        {/* <Progress percent={50} size="small" status="active" /> */}
        {isShowProgress && SpinLoading()}
        <Toolbar >
          <Item location="before"
            locateInMenu="never"
            render={() => (
              <div className="toolbar-label"
                style={{
                  marginLeft: '4px',
                  fontSize: '16px',
                  fontWeight: 700,
                }}>
                <span> {intl('pro.HeaderTitle', '本地项目列表')}</span>
              </div>
            )} />
          <Item location="after">
            {/* <DropDownButton
              text={intl('pro.ProjectResults', '项目成果')}
              items={['成果导入', '成果导出']}
              onItemClick={onItemClickAchievements}
            /> */}
            <DropDownButton
              className='devDropDownButton'
              // dropDownOptions={{
              //   width: 120
              // }}
              text={intl('pro.ProjectDistribution', '项目分发')}
              items={['项目导入', '项目导出']}
              onItemClick={onItemClickProject}
            />
          </Item>
        </Toolbar>
        <SelZcbfPopupMemo ref={selZcbfPopupRef} />
      </div>
    </>
  );
}

export default ToolHead;
